//
//  NSObject+Theme.swift
//  HeadlineNews
//
//  Created by han on 2019/7/24.
//  Copyright © 2019 han. All rights reserved.
//

import UIKit

private typealias setCGColorValueIMP = @convention(c) (NSObject, Selector, CGColor) -> Void
private typealias setCGFloatValueIMP = @convention(c) (NSObject, Selector, CGFloat) -> Void


// MARK: -
typealias ThemePickers = [String: ThemePicker]
private var themePickersKey = ""

extension NSObject {
    var themePickers: ThemePickers {
        get {
            if let themePickers = objc_getAssociatedObject(self, &themePickersKey) as? ThemePickers {
                return themePickers
            }
            let initValue = ThemePickers()
            objc_setAssociatedObject(self, &themePickersKey, initValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
            return initValue
        }
        set {
            objc_setAssociatedObject(self, &themePickersKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
            //            _removeThemeNotification()
            //            if newValue.isEmpty == false { _setupThemeNotification() }
        }
    }
}

extension NSObject: ThemeExtendProtocol{}
extension ThemeExtended where T: NSObject {
   
    
    func performPicker(selector: String, picker: ThemePicker?) {
        let sel = Selector(selector)
        
        guard value.responds(to: sel) else { return }
        
        guard let pickerValue = picker?.value() else { return }
        
        if let statePicker = picker as? ThemeStatePicker {
            
        } else if picker is ThemeCGColorPicker {
            // 将selector强制转换为 setCGColorValueIMP这种类型的
            let setCGColor = unsafeBitCast(value.method(for: sel), to: setCGColorValueIMP.self)
            setCGColor(value, sel, pickerValue as! CGColor)
        } else if picker is ThemeCGFloatPicker {
            let setCGFloat = unsafeBitCast(value.method(for: sel), to: setCGFloatValueIMP.self)
            setCGFloat(value, sel, pickerValue as! CGFloat)
        }
        else {
            value.perform(sel, with: pickerValue)
        }
        
    }
    
}
